﻿using System;
using System.Collections.Generic;
using System.Reflection;
using FairyGUI;

namespace GameMenuControlPlatform
{
	public partial class UIControllerManager 
	{
		private static Dictionary<UIControllerName, UIController> m_controllers = new Dictionary<UIControllerName, UIController>();

        public static void CloseAllPages()
        {
            foreach(var page in m_controllers)
            {
                page.Value.CloseView(false);
            }
        }
		public static void AddController(UIControllerName controllerName, UIController controller)
		{
			m_controllers.Add(controllerName, controller);
		}
		public static void DestroyController(UIControllerName controllerName)
		{ 
            m_controllers.Remove(controllerName);
		}

		private static UIController GetController(UIControllerName controllerName)
		{
			if (m_controllers.ContainsKey(controllerName))
			{
				return m_controllers[controllerName];
			}
			return null;
		}

		public static T1 GetController<T1, T2>(UIControllerName name) 
			where T1 : UIController 
			where T2 : GComponent
		{
			T1 controller = GetController(name) as T1;
			if (controller == null)
			{
				T2 view = typeof(T2).GetMethod("CreateInstance",BindingFlags.Public |BindingFlags.Static).Invoke(null, null) as T2;
				ConstructorInfo ctor = typeof(T1).GetConstructor(new System.Type[] { typeof(T2) });
				controller =ctor.Invoke(new object[] { view }) as T1;
				controller.SetName (name);
				m_controllers.Add(name, controller);
			}
			return controller;
		}
        
        public static UIController OpenPage(UIControllerName pagename)
        {
            Type controllertype = controllerTypeMaps[pagename];
            Type uitype = uiTypeMaps[pagename];

            UIController controller = GetController(pagename);
            if(controller == null)
            {
                GComponent view = uitype.GetMethod("CreateInstance", BindingFlags.Public | BindingFlags.Static).Invoke(null, null) as GComponent;
                ConstructorInfo ctor = controllertype.GetConstructor(new System.Type[] { uitype });
                controller = ctor.Invoke(new object[] { view }) as UIController;
                controller.SetName(pagename);
                m_controllers.Add(pagename, controller);
            }
            controller.OpenView();
            return controller;
        }
        public static void ClosePage(UIControllerName pagename)
        {
            UIController controller = GetController(pagename);
            if(controller != null)
            {
                controller.CloseView();
            }
        }
        public static UIController GetPage(UIControllerName pagename)
        {
            return GetController(pagename);
        }
    }
}

